package com.staff.service;

import java.util.ArrayList;
import java.util.List;

import javax.transaction.Transactional;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import com.staff.dao.StaffArchiveRepository;
import com.staff.entity.StaffArchive;
import com.staff.entity.dto.StaffArchiveQueryDTO;

@Service
@Transactional
public class StaffArchiveService implements IStaffArchiveService {
	@Autowired
	private StaffArchiveRepository staffArchiveRepository;
	
	@Override
	public void saveOrUpdate(StaffArchive staffArchive) {
		staffArchiveRepository.save(staffArchive);
	}

	@Override
	public void delete(StaffArchive staffArchive) {
		staffArchive=staffArchiveRepository.findOne(staffArchive.getId());
		if(staffArchive!=null) {
			staffArchive.setStaff(null);
			staffArchiveRepository.save(staffArchive);
		}
		staffArchiveRepository.delete(staffArchive);
	}

	@Override
	public StaffArchive findOne(Long id) {
		return staffArchiveRepository.findOne(id);
	}

	@Override
	public List<StaffArchive> findAll() {
		return (List<StaffArchive>) staffArchiveRepository.findAll();
	}

	@Override
	public void delete(List<Long> ids) {
		List<StaffArchive> staffArchiveList = (List<StaffArchive>)staffArchiveRepository.findAll(ids);
		for(StaffArchive staffArchive : staffArchiveList) {
			staffArchive.setStaff(null);
			staffArchiveRepository.save(staffArchive);
		}
			staffArchiveRepository.delete(staffArchiveList);
		
	}

	@Override
	public Page<StaffArchiveQueryDTO> findAll(Specification<StaffArchive> spec, Pageable pageable) {
		//将员工档案page转化为员工档案DTOpage
		List<StaffArchiveQueryDTO> results = new ArrayList<StaffArchiveQueryDTO>();
		Page<StaffArchive> page = staffArchiveRepository.findAll(spec, pageable);
		for(StaffArchive sa:page.getContent()) {
			StaffArchiveQueryDTO saDTO = new StaffArchiveQueryDTO(sa, sa.getStaff());
        	results.add(saDTO);
		}
		return new PageImpl<StaffArchiveQueryDTO>(results, pageable, results.size());
	}

}
